<template>
    <el-button type="primary"
               size="small"
               icon="el-icon-download"
               @click="exportExcel">导出Excel</el-button>
</template>

<script>

  import request from '@/router/axios';

  export default {
    name: "excelExport",
    props: {
      loading: {
        type: Boolean,
        default: true
      },
      loadingText: {
        type: String,
        default: "正在导出Excel，请耐心等待。。。"
      },
      exportUrl: {
        type: String,
        default: "",
        required: true
      },
      excelName: {
        type: String,
        default: "导出数据"
      },
      prepareQuery: Function
    },
    methods: {
      async exportExcel() {
        let loading;
        if(this.loading) {
          loading = this.$loading({
            lock: true,
            text: this.loadingText || "正在导出Excel，请耐心等待。。。",
            spinner: "el-icon-loading"
          });
        }

        let query = {};
        let result;
        if(!this.prepareQuery) {
          result = await this.post();
        }else {
          query = this.prepareQuery();
          if(Object.prototype.toString.call(query).toLowerCase() === '[object object]') {
            result = await this.post(query);
          }else {
            result = await this.post()
          }
        }

        const url = window.URL.createObjectURL(new Blob([result.data], { type: 'application/octet-stream'}));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', this.excelName + ".xlsx" || "导出数据.xlsx");
        document.body.appendChild(link);
        link.click();

        if(loading) {
          this.$nextTick(() => {
            loading.close()
          })
        }
      },
      async post(query = {}) {
        return await request({
          url: this.exportUrl,
          method: 'post',
          responseType: 'blob',
          timeout: 60000,
          params: query
        });
      }
    }
  }
</script>

<style scoped>

</style>